import random
from statistics import mode
import sys
import argparse
import subprocess
import cv2
from keras.models import load_model
import numpy as np
from utils.camfig import open_cam_onboard

from utils.datasets import get_labels
from utils.inference import detect_faces
from utils.inference import draw_text
from utils.inference import draw_bounding_box
from utils.inference import apply_offsets
from utils.inference import load_detection_model
from utils.preprocessor import preprocess_input


if __name__ == '__main__':
    #人脸识别模型路径，表情识别模型路径
    detection_model_path = '../trained_models/detection_models/haarcascade_frontalface_default.xml'
    emotion_model_path = '../trained_models/emotion_models/fer2013_mini_XCEPTION.102-0.66.hdf5'
    emotion_labels = get_labels('fer2013')
    #
    frame_window = 10
    emotion_offsets = (20, 40)
    # 导入人脸识别模型和表情识别模型
    face_detection = load_detection_model(detection_model_path)
    emotion_classifier = load_model(emotion_model_path, compile=False)
    # getting input model shapes for inference
    emotion_target_size = emotion_classifier.input_shape[1:3]
    # print('emotion_target_size:', emotion_target_size)
    # starting lists for calculating modes
    emotion_window = []

    #开始视频流
    video_capture = cv2.VideoCapture(0) #使用开发设备的摄像头
    # video = open_cam_onboard(760,480) #使用Jetson Nano设备板载摄像头，分辨率可以自由设置
    # video_capture = cv2.VideoCapture(video)
    print('相机已打开')
    WINDOW_NAME = '人脸表情识别测试'
    while True:
        #导入视频流
        bgr_image = video_capture.read()[1]
        #将视频翻转180度
        # bgr_image= cv2.flip(bgr_image,-1)
        #灰度图像
        gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
        gray_image = cv2.equalizeHist(gray_image) #直方图均衡化方法，减少光照的影响
        rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
        #人脸识别
        faces = detect_faces(face_detection, gray_image)
        #表情分类
        for face_coordinates in faces:
            x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)
            gray_face = gray_image[y1:y2, x1:x2]
            try:
                gray_face = cv2.resize(gray_face, (emotion_target_size))
            except:
                continue

            gray_face = preprocess_input(gray_face, True)
            gray_face = np.expand_dims(gray_face, 0)
            gray_face = np.expand_dims(gray_face, -1)
            emotion_prediction = emotion_classifier.predict(gray_face)
            emotion_probability = np.max(emotion_prediction)
            emotion_label_arg = np.argmax(emotion_prediction)
            emotion_text = emotion_labels[emotion_label_arg]
            emotion_window.append(emotion_text)

            if len(emotion_window) > frame_window:
                emotion_window.pop(0)
            try:
                emotion_mode = mode(emotion_window)
            except:
                continue
            #设置字体的颜色
            if emotion_text == 'angry':
                color = emotion_probability * np.asarray((0, 0, 255))
            elif emotion_text == 'sad':
                color = emotion_probability * np.asarray((255, 0, 0))
            elif emotion_text == 'happy':
                color = emotion_probability * np.asarray((255, 255, 0))
            elif emotion_text == 'surprise':
                color = emotion_probability * np.asarray((0, 255, 255))
            elif emotion_text == 'disgust':
                color = emotion_probability * np.asarray((255,255,120))
            else:
                color = emotion_probability * np.asarray((0, 255, 0))

            color = color.astype(int)
            color = color.tolist()
            #画人脸框图
            draw_bounding_box(face_coordinates, rgb_image, color)
            draw_text(face_coordinates, rgb_image, emotion_mode,
                      color, 0, -45, 1, 1)

        bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
        key = cv2.waitKey(10)
        if key == 27:  # ESC key: quit program
            break
        elif key == ord('F') or key == ord('f'):  # toggle fullscreen
            #是否全屏显示
            cv2.setWindowProperty(WINDOW_NAME, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
            print('f')
        elif key == ord('J') or key == ord('j'):
            cv2.imwrite('image/' + str(random.sample(range(0, 1000), 1)) + 'w.jpg', bgr_image)
            print('截图成功')

        #显示处理后的图像
        cv2.imshow(WINDOW_NAME, bgr_image)
    #释放视频流
    video_capture.release()
    cv2.destroyAllWindows()